import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import '../platform/platform_detector.dart';

/// Dio配置类
class DioConfig {
  /// 创建配置好的Dio实例
  static Dio createDio([Future<String?> Function()? tokenProvider]) {
    final dio = Dio();

    // 基础配置
    dio.options = BaseOptions(
      baseUrl: _getBaseUrl(),
      connectTimeout: const Duration(seconds: 30),
      receiveTimeout: const Duration(seconds: 30),
      sendTimeout: const Duration(seconds: 30),
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
      },
    );

    // 添加拦截器
    dio.interceptors.addAll([
      // 日志拦截器（仅在调试模式下）
      if (kDebugMode) ...[
        LogInterceptor(
          request: true,
          requestHeader: true,
          requestBody: true,
          responseHeader: true,
          responseBody: true,
          logPrint: (obj) => debugPrint(obj.toString()),
        ),
      ],

      // 请求拦截器
      InterceptorsWrapper(
        onRequest: (options, handler) async {
          // 记录请求日志
          if (kDebugMode) {
            debugPrint('=== API Request ===');
            debugPrint('Method: ${options.method}');
            debugPrint('URL: ${options.uri}');
            debugPrint('Headers: ${options.headers}');
            if (options.data != null) {
              debugPrint('Body: ${options.data}');
            }
          }

          // 添加认证Token到请求头
          try {
            final token = await tokenProvider?.call();

            if (token != null) {
              options.headers['Authorization'] = 'Bearer $token';
              if (kDebugMode) {
                debugPrint('添加认证Token到请求头');
              }
            } else if (kDebugMode) {
              debugPrint('未找到认证Token');
            }
          } catch (e) {
            if (kDebugMode) {
              debugPrint('获取认证Token时出错: $e');
            }
          }

          return handler.next(options);
        },
        onResponse: (response, handler) {
          // 记录响应日志
          if (kDebugMode) {
            debugPrint('=== API Response ===');
            debugPrint('Status Code: ${response.statusCode}');
            debugPrint('URL: ${response.realUri}');
            if (response.data != null) {
              debugPrint('Response: ${response.data}');
            }
          }
          return handler.next(response);
        },
        onError: (DioException error, handler) {
          // 记录错误日志
          if (kDebugMode) {
            debugPrint('=== API Error ===');
            debugPrint('Error Type: ${error.type}');
            debugPrint('Error Message: ${error.message}');
            if (error.response != null) {
              debugPrint('Status Code: ${error.response?.statusCode}');
              debugPrint('Response Data: ${error.response?.data}');
            }

            // 特别处理连接错误
            if (error.type == DioExceptionType.connectionError) {
              debugPrint('网络连接错误，请检查网络设置或稍后重试');
            }
          }
          return handler.next(error);
        },
      ),
    ]);

    return dio;
  }

  /// 获取基础URL
  static String _getBaseUrl() {
    // 根据不同环境返回不同的基础URL
    // 这里可以读取环境变量或配置文件
    if (PlatformDetector.isWeb()) {
      // Web端可能需要不同的基础URL
      return 'http://localhost:8080/api';
    } else {
      // 移动端/桌面端
      return 'http://localhost:8080/api';
    }
  }
}
